package com.cy.aircompressor.main.home.fragment.v2;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Observer;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.blankj.utilcode.util.TimeUtils;
import com.cy.aircompressor.R;
import com.cy.aircompressor.config.AirConfig;
import com.cy.aircompressor.databinding.FragmentContentMainV2Binding;
import com.cy.aircompressor.entity.compressor.Compressor;
import com.cy.aircompressor.entity.maintenance.MaintenanceRecord;
import com.cy.aircompressor.entity.select.SelectDict;
import com.cy.aircompressor.entity.sensor.Sensor;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.sensor.SensorStatisticsData;
import com.cy.aircompressor.entity.warning.WarningMsg;
import com.cy.aircompressor.main.home.dialog.ModifyPwdDialog;
import com.cy.aircompressor.main.home.fragment.MaintenanceMoreDialogFragment;
import com.cy.aircompressor.main.home.lifecycle.LifeCycleDialogFragment;
import com.cy.aircompressor.main.home.other.WarningFragment;
import com.cy.aircompressor.main.home.systemsetting.fragment.SystemSettingFragment;
import com.cy.aircompressor.main.home.viewmodel.MainContentViewModel;
import com.cy.aircompressor.main.view.BottomBar;
import com.cy.aircompressor.main.view.dialog.DateTimePickerDialog;
import com.cy.aircompressor.main.view.pop.ExitPopupWindow;
import com.cy.aircompressor.utils.JumpPageUtils;
import com.drug.lib.util.DLog;
import com.drug.lib.util.SPManager;
import com.drug.lib.util.ToastUtil;
import com.drug.lib.view.recycptr.bean.RowEntity;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.Resource;
import com.net.model.base.fragment.BaseVMFragment;
import com.net.model.utils.Constant;
import com.youth.banner.listener.OnPageChangeListener;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MainContentFragmentV2 extends BaseVMFragment<FragmentContentMainV2Binding, MainContentViewModel> {

    private int currentPosition = 0;
    private MainContentHelperV2 mainContentHelper;
    private ModifyPwdDialog modifyPwdDialog;

    public static MainContentFragmentV2 newInstance() {
        Bundle args = new Bundle();
        MainContentFragmentV2 fragment = new MainContentFragmentV2();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    protected FragmentContentMainV2Binding getViewBinding() {
        return FragmentContentMainV2Binding.inflate(getLayoutInflater());
    }

    @Override
    protected void initData() {
        initView();
        mainContentHelper = MainContentHelperV2.get();
        mainContentHelper.init(mBinding, this, mContext);
        LineChartHelper.get().setFragmentManager(getChildFragmentManager());
        LineChartHelper.get().initLineChartScrollViewDatas(mBinding.lineChartScrollView,false);
        LineChartHelper.get().initLineChartScrollViewDatas(mBinding.vibrationLineChart,true);
    }

    @Override
    protected void requestNetwork() {
        if (AirConfig.get().userInfo != null) {
            mViewModel.compressor(AirConfig.get().userInfo.getPowerStationId());
            mViewModel.queryAllSensorByPage(AirConfig.get().userInfo.getPowerStationId());
            mViewModel.queryWarningCount();
        }
    }

    private void initView() {
        mBinding.selectDateLayout.setVisibility(isHistory ? View.VISIBLE : View.GONE);
        RxView.clicks(mBinding.userInfoLayout)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    List<SelectDict> selectDicts = new ArrayList<>();
                    SelectDict selectDict = new SelectDict();
                    selectDict.setLabel("修改密码");
                    selectDict.setValue("modify_password");
                    selectDicts.add(selectDict);
                    selectDict = new SelectDict();
                    selectDict.setLabel("退出登录");
                    selectDict.setValue("exit_login");
                    selectDicts.add(selectDict);
                    ExitPopupWindow exitPopupWindow = new ExitPopupWindow(mContext, mBinding.userInfoLayout, selectDicts);
                    exitPopupWindow.showAsBelow(mBinding.userInfoLayout, 0, 5);
                    exitPopupWindow.setDropdownCallBack(new ExitPopupWindow.DropdownCallBack() {
                        @Override
                        public void select(SelectDict selectDict) {
                            if (TextUtils.equals(selectDict.getValue(), "modify_password")) {
                                modifyPwdDialog = ModifyPwdDialog.showDialogFragment(getChildFragmentManager(), "Modify");
                                modifyPwdDialog.setModifyPwdCallBack(new ModifyPwdDialog.ModifyPwdCallBack() {
                                    @Override
                                    public void result(Object object) {
                                        mViewModel.updatePwd(object);
                                    }
                                });

                            } else if (TextUtils.equals(selectDict.getValue(), "exit_login")) {
                                showDialog();
                            }
                        }
                    });
                });
        mBinding.bottomBar.setOnTabSelectedListener(new BottomBar.OnTabSelectedListener() {
            @Override
            public void onTabSelected(int position, int prePosition) {

                switch (position) {
                    case 0:
                        isHistory = false;
                        mBinding.leftTextTitle.setText(getString(R.string.nav_zxjc));
                        mBinding.rightTextTitle.setText(getString(R.string.nav_zxjc));
                        mainContentHelper.setNewQueryDate(isHistory);
                        mainContentHelper.resetAllUi(false);
                        querySensorRelatedData();

                        break;
                    case 1:
                        isHistory = true;
                        mBinding.leftTextTitle.setText(getString(R.string.nav_sjfx));
                        mBinding.rightTextTitle.setText(getString(R.string.nav_sjfx));
                        mainContentHelper.setNewQueryDate(isHistory);
                        mainContentHelper.resetAllUi(false);
                        querySensorRelatedData();
                        break;
                    case 2:
                        LifeCycleDialogFragment lifeCycleDialogFragment = LifeCycleDialogFragment.showDialogFragment(getChildFragmentManager(), "lifecycle", mainContentHelper.currentCompressor.getId());
                        lifeCycleDialogFragment.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mBinding.bottomBar.setCurrentItem(isHistory ? 1 : 0);
                            }
                        });
                        break;
                    case 3:
                        SystemSettingFragment settingFragment = SystemSettingFragment.showDialogFragment(getChildFragmentManager(), "system_setting");
                        settingFragment.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mBinding.bottomBar.setCurrentItem(isHistory ? 1 : 0);
                            }
                        });
                        break;
                }
                mBinding.selectDateLayout.setVisibility(isHistory ? View.VISIBLE : View.GONE);
            }

            @Override
            public void onTabUnselected(int position) {
            }

            @Override
            public void onTabReselected(int position) {
            }
        });
        mBinding.banner.addOnPageChangeListener(new OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                mainContentHelper.setCurrentCompressor(mainContentHelper.compressors.get(position));
                mBinding.bottomBar.setCurrentItem(0);
                mainContentHelper.resetAllUi(true);
                queryCompressorRelatedData();


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        RxView.clicks(mBinding.selectDateLayout)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    showDatePicker();
                });
        RxView.clicks(mBinding.warningHis)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    WarningFragment.showDialogFragment(getChildFragmentManager(), "3", mainContentHelper.currentCompressor.getId());
                });
        RxView.clicks(mBinding.moreMaintenance)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    MaintenanceMoreDialogFragment.showDialogFragment(getChildFragmentManager(), "more", mainContentHelper.currentCompressor.getId());
                });

    }

    @Override
    protected void dataChange() {

        mViewModel.getUpdatePwdObservable().observe(this, new Observer<Resource<Object>>() {
            @Override
            public void onChanged(Resource<Object> objectResource) {
                objectResource.handler(new OnCallback<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        ToastUtil.show("修改成功，重新登陆");
                        if (modifyPwdDialog != null) {
                            modifyPwdDialog.dismiss();
                        }
                        SPManager.removePassword();
                        JumpPageUtils.jumpLogin();
                    }
                });
            }
        });

        mViewModel.getLogoutObservable().observe(this, new Observer<Resource<Object>>() {
            @Override
            public void onChanged(Resource<Object> objectResource) {
                objectResource.handler(new OnCallback<Object>() {
                    @Override
                    public void onSuccess(Object data) {
                        SPManager.removePassword();
                        AirConfig.get().release();
                        JumpPageUtils.jumpLogin();
                    }
                });
            }
        });


        mViewModel.getQueryAllSensorByPage().

                observe(this, new Observer<Resource<RowEntity<Sensor>>>() {
                    @Override
                    public void onChanged(Resource<RowEntity<Sensor>> rowEntityResource) {
                        rowEntityResource.handler(new OnCallback<RowEntity<Sensor>>() {
                            @Override
                            public void onSuccess(RowEntity<Sensor> data) {
                                mBinding.sensorNum.setText(String.valueOf(data.getTotal()));
                            }
                        });
                    }
                });

        mViewModel.getWarningObservable().

                observe(this, new Observer<Resource<Integer>>() {
                    @Override
                    public void onChanged(Resource<Integer> integerResource) {
                        integerResource.handler(new OnCallback<Integer>() {
                            @Override
                            public void onSuccess(Integer data) {
                                mBinding.warningNum.setText(data.intValue() + "");
                            }
                        });
                    }
                });

        mViewModel.getQueryWarningByPageObservable().

                observe(this, new Observer<Resource<RowEntity<WarningMsg>>>() {
                    @Override
                    public void onChanged(Resource<RowEntity<WarningMsg>> rowEntityResource) {
                        rowEntityResource.handler(new OnCallback<RowEntity<WarningMsg>>() {
                            @Override
                            public void onSuccess(RowEntity<WarningMsg> data) {
                                mainContentHelper.warningMsgAdapter.setItems(data.getList());
                                mainContentHelper.warningMsgAdapter.notifyDataSetChanged();
                                mBinding.warningNodata.dismiss();
                                mBinding.warningRecyc.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFailure(Integer code, String message) {
                                super.onFailure(code, message);
                                if (code == Constant.EMPTY_DATA_ERROR) {
                                    mainContentHelper.warningMsgAdapter.setItems(new ArrayList<>());
                                    mainContentHelper.warningMsgAdapter.notifyDataSetChanged();
                                    mBinding.warningNodata.show();
                                    mBinding.warningRecyc.setVisibility(View.GONE);
                                }
                            }
                        });
                    }
                });

        mViewModel.getQueryMaintenanceRecordByPageObservable().

                observe(this, new Observer<Resource<RowEntity<MaintenanceRecord>>>() {
                    @Override
                    public void onChanged(Resource<RowEntity<MaintenanceRecord>> rowEntityResource) {
                        rowEntityResource.handler(new OnCallback<RowEntity<MaintenanceRecord>>() {
                            @Override
                            public void onSuccess(RowEntity<MaintenanceRecord> data) {
                                mainContentHelper.maintenanceRecordAdapter.setItems(data.getList());
                                mainContentHelper.maintenanceRecordAdapter.notifyDataSetChanged();
                                mBinding.maintenanceNodata.dismiss();
                                mBinding.maintenanceRecordRecyc.setVisibility(View.VISIBLE);
                                mBinding.titleLy.setVisibility(View.VISIBLE);
                            }

                            @Override
                            public void onFailure(Integer code, String message) {
                                super.onFailure(code, message);
                                if (code == Constant.EMPTY_DATA_ERROR) {
                                    mainContentHelper.maintenanceRecordAdapter.setItems(new ArrayList<>());
                                    mainContentHelper.maintenanceRecordAdapter.notifyDataSetChanged();

                                    mBinding.maintenanceNodata.show();
                                    mBinding.maintenanceRecordRecyc.setVisibility(View.GONE);
                                    mBinding.titleLy.setVisibility(View.GONE);
                                }
                            }
                        });
                    }
                });


        mViewModel.getCompressorObservable().

                observe(this, new Observer<Resource<RowEntity<Compressor>>>() {
                    @Override
                    public void onChanged(Resource<RowEntity<Compressor>> rowEntityResource) {
                        rowEntityResource.handler(new OnCallback<RowEntity<Compressor>>() {
                            @Override
                            public void onSuccess(RowEntity<Compressor> data) {
                                mainContentHelper.compressors = data.getList();
                                mainContentHelper.setCurrentCompressor(mainContentHelper.compressors.get(currentPosition));
                                mainContentHelper.setCompressorToUi(data.getTotal());
                                mBinding.banner.setDatas(mainContentHelper.compressors);
                                queryCompressorRelatedData();
                            }
                        });
                    }
                });
        mViewModel.getQuerySensorByPage().

                observe(this, new Observer<Resource<RowEntity<Sensor>>>() {
                    @Override
                    public void onChanged(Resource<RowEntity<Sensor>> rowEntityResource) {
                        rowEntityResource.handler(new OnCallback<RowEntity<Sensor>>() {
                            @Override
                            public void onSuccess(RowEntity<Sensor> data) {
                                mainContentHelper.setCurrentSensors(data.getList());
                                if (mainContentHelper.currentSensors != null && mainContentHelper.currentSensors.size() != 0) {
                                    querySensorRelatedData();
                                }
                            }

                            @Override
                            public void onFailure(Integer code, String message) {
                                super.onFailure(code, message);
                                if (code == Constant.EMPTY_DATA_ERROR) {
                                    DLog.e("------当前空压机未安装有传感器------");
                                }
                            }
                        });
                    }
                });


        mViewModel.getQuerySensorStatisticsDataDataObservable().

                observe(this, new Observer<Resource<List<SensorStatisticsData>>>() {
                    @Override
                    public void onChanged(Resource<List<SensorStatisticsData>> listResource) {
                        listResource.handler(new OnCallback<List<SensorStatisticsData>>() {
                            @Override
                            public void onSuccess(List<SensorStatisticsData> data) {
                                mainContentHelper.setStatisticsDataList(data);
                                checkLoadFinish();
                            }

                            @Override
                            public void onFailure(Integer code, String message) {
                                super.onFailure(code, message);
                                checkLoadFinish();
                            }
                        });
                    }
                });


        mViewModel.getQueryCompressorSensorDataObservable().

                observe(this, new Observer<Resource<List<SensorLatestData>>>() {
                    @Override
                    public void onChanged(Resource<List<SensorLatestData>> sensorDataResource) {
                        sensorDataResource.handler(new OnCallback<List<SensorLatestData>>() {
                            @Override
                            public void onSuccess(List<SensorLatestData> data) {
                                mainContentHelper.setLatestDataList(data);
                                checkLoadFinish();
                            }

                            @Override
                            public void onFailure(Integer code, String message) {
                                super.onFailure(code, message);
                                checkLoadFinish();
                            }
                        });
                    }
                });
    }


    /**
     * 检查本次加载是否完成
     */
    public void checkLoadFinish() {
        mainContentHelper.readyNo++;
        DLog.e("====数据加载进度=" + mainContentHelper.readyNo);
        if (mainContentHelper.readyNo == (mainContentHelper.currentSensors.size() + 1)) {
            DLog.e("数据加载完成准备刷新...");
            mBinding.lineChartScrollView.notifyAllDataSetChanged();
            mBinding.vibrationLineChart.notifyAllDataSetChanged();
            mainContentHelper.readyNo = 0;
            dismissDialog();
        }
    }

    /**
     * 根据传感器获取传感器统计数据
     */
    private void loadSensorStatisticsData() {
        if (mainContentHelper.currentSensors == null) {
            return;
        }
        DLog.e("------获取空压机最近一小时数据------");
        DLog.e("------空压机安装传感器数量：------" + mainContentHelper.currentSensors.size());
        for (Sensor sensor : mainContentHelper.currentSensors) {
            mViewModel.querySensorStatisticsData(mainContentHelper.startTime, mainContentHelper.endTime, sensor.getSn(), Integer.parseInt(sensor.getType()));
        }
//        getHandler().postDelayed(loadSensorDataRunnable, 60 * 1000);
    }

    Runnable loadSensorDataRunnable = new Runnable() {
        @Override
        public void run() {
            loadSensorStatisticsData();
        }
    };


    /**
     * 查询空压机相关数据 告警，维保，所属所有传感器
     */
    private void queryCompressorRelatedData() {
        mainContentHelper.setNewQueryDate(isHistory);
        if (mainContentHelper.currentCompressor != null) {
            mViewModel.queryMaintenanceRecordByPage(mainContentHelper.currentCompressor.getId());
            mViewModel.queryWarningByPage(mainContentHelper.currentCompressor.getId());
            mViewModel.querySensorByPage(mainContentHelper.currentCompressor.getId(), AirConfig.get().userInfo.getPowerStationId());
        }
    }

    private boolean isHistory = false;

    /**
     * 查询传感器相关数据
     */
    private void querySensorRelatedData() {
        if (mainContentHelper.currentCompressor == null) return;
        if (mainContentHelper.currentSensors != null && mainContentHelper.currentSensors.size() != 0) {
            showLoading();
            queryCompressorNewData();
            loadSensorStatisticsData();
        }

    }

    /**
     * 查询当前空压机最新数据
     */
    private void queryCompressorNewData() {
        if (mainContentHelper.currentCompressor == null) {
            return;
        }
        DLog.e("------启动定时器，获取空压机最新数据------");
        List<String> list = new ArrayList<>();
        list.add(mainContentHelper.currentCompressor.getId());
        mViewModel.queryCompressorSensorRealTimeData(list);
//        getHandler().postDelayed(compressorNewDataRunnable, 60 * 1000);
    }

    Runnable compressorNewDataRunnable = new Runnable() {
        @Override
        public void run() {
            queryCompressorNewData();
        }
    };


    private void showDatePicker() {
        long minDate = 0l;
        if (mainContentHelper.currentCompressor != null) {
            String installDate = mainContentHelper.currentCompressor.getInstallDate();
            if (!TextUtils.isEmpty(installDate)) {
                minDate = TimeUtils.string2Date(installDate, "yyyy-MM-dd").getTime();
            }
        }
        DateTimePickerDialog dateTimePickerDialog = DateTimePickerDialog.showDialogFragment(getChildFragmentManager(), "date_select", minDate);
        dateTimePickerDialog.setDateTimeSelectCallBack(new DateTimePickerDialog.DateTimeSelectCallBack() {
            @Override
            public void selectDate(String startTime, String endTime) {
                mainContentHelper.setStartEndTime(startTime, endTime);
                querySensorRelatedData();
            }

            @Override
            public void cancelSelect() {

            }
        });
    }

    private void showDialog() {
        new MaterialDialog.Builder(mContext)
                .title("提示")
                .content("您确定退出当前登录？")
                .positiveText("退出登录")
                .negativeText("取消")
                .canceledOnTouchOutside(false)
                .contentColor(ContextCompat.getColor(mContext, R.color.text_color_lg))
                .titleColor(ContextCompat.getColor(mContext, R.color.colorAccent))
                .backgroundColor(ContextCompat.getColor(mContext, R.color.default_background))
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        mViewModel.logout();
                        dialog.dismiss();
                    }
                })
                .show();
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        mBinding.banner.start();
    }

    @Override
    public void onStop() {
        super.onStop();
        //停止轮播
        mBinding.banner.stop();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //销毁
        mBinding.banner.destroy();
    }
}
